import { useState, useEffect } from 'react'
import StockTable from './StockTable'
import { Select, Spin } from 'antd'
import { fetchStrategyInfo, fetchStrategyStocks } from '../api/strategies'

export default function Sidebar({ onStockSelect, onDateChange }: any) {
  const [strategyOptions, setStrategyOptions] = useState<any[]>([])
  const [reportDateOptions, setReportDateOptions] = useState<any[]>([])
  const [stockData, setStockData] = useState<any[]>([])

  const [selectedStrategyID, setSelectedStrategyID] = useState<number | null>(null)
  const [selectedDate, setSelectedDate] = useState<string | null>(null)
  const [loading, setLoading] = useState<boolean>(false)

  /* 初始化加载策略与报告期 */
  useEffect(() => {
    const loadStrategyInfo = async () => {
      setLoading(true)
      try {
        const res = await fetchStrategyInfo()
        const { strategyList = [], reportDate = [] } = res.data || {}

        const strategies = strategyList.map((s: any) => ({
          value: s.strategyID,
          label: s.strategyName
        }))
        const dates = reportDate.map((d: string) => ({
          value: d,
          label: d
        }))

        setStrategyOptions(strategies)
        setReportDateOptions(dates)

        // 设置默认选中第一个策略 & 报告期
        if (strategies.length > 0) {
          setSelectedStrategyID(strategies[0].value)
          // onStrategyChange?.(strategies[0].value)
        }
        if (dates.length > 0) {
          setSelectedDate(dates[0].value)
          onDateChange?.(dates[0].value)
        }
      } catch (err) {
        console.error('获取策略信息失败:', err)
      } finally {
        setLoading(false)
      }
    }

    loadStrategyInfo()
  }, [])

  /** 策略或报告期变化时动态获取股票列表 */
  useEffect(() => {
    const loadStocks = async () => {
      if (!selectedStrategyID || !selectedDate) return
      setLoading(true)
      try {
        const res = await fetchStrategyStocks(selectedStrategyID, selectedDate)
        setStockData(res.data || [])
      } catch (err) {
        console.error('获取策略选股结果失败:', err)
        setStockData([])
      } finally {
        setLoading(false)
      }
    }

    loadStocks()
  }, [selectedStrategyID, selectedDate])

  const handleStrategyChange = (value: number) => {
    setSelectedStrategyID(value)
    // onStrategyChange?.(value)
  }

  const handleDateChange = (value: string) => {
    setSelectedDate(value)
    onDateChange?.(value)
  }

  return (
    <div className="border-r bg-white shadow-sm p-4 overflow-y-auto h-full">
      <h2 className="text-xl font-bold mb-4">策略选股结果</h2>

      <div className="mb-4 flex gap-6">
        <div className="flex-1 min-w-0">
          <Select
            showSearch
            allowClear={false}
            className="w-full"
            placeholder="请选择策略"
            optionFilterProp="label"
            options={strategyOptions}
            value={selectedStrategyID ?? undefined}
            onChange={handleStrategyChange}
          />
        </div>
        <div className="w-[50%] min-w-0">
          <Select
            className="w-full"
            placeholder="报告日期"
            options={reportDateOptions}
            value={selectedDate ?? undefined}
            onChange={handleDateChange}
          />
        </div>
      </div>

      <Spin spinning={loading}>
        <StockTable data={stockData} reportDate={selectedDate} onAskAI={onStockSelect} />
      </Spin>
    </div>
  )
}
